package org.ww.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.ww.edu.bean.Subject;
import org.ww.edu.bean.excel.ExcelSubject;
import org.ww.edu.service.SubjectService;
import org.ww.servicebase.exceptionhandler.GuliException;

import java.util.Map;

public class SubjectExcelListener extends AnalysisEventListener<ExcelSubject> {

    //该类没法交给spring去管理，所以也不能去注入对象
    //手动new
    private SubjectService subjectService;

    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }
    public SubjectExcelListener() {
    }

    //一行一行读取
    @Override
    public void invoke(ExcelSubject data, AnalysisContext analysisContext) {

        if(data==null){
            throw new GuliException(20001,"数据表为空");
        }

        //添加一级分类
        //判断一级分类是否有相同的
        Subject oneSubject = isExistOneSubject(subjectService, data.getOneSubjectName());
        if(oneSubject==null){
            oneSubject=new Subject();
            oneSubject.setTitle(data.getOneSubjectName());
            oneSubject.setParentId("0");
            subjectService.save(oneSubject);
        }

        //获取一级分类id
        String pid = oneSubject.getId();

        //添加二级分类
        Subject twoSubject = isExistTwoSubject(subjectService, data.getTwoSubjectName(), pid);
        //判读二级分类是否存在
        if(twoSubject==null){
            twoSubject=new Subject();
            twoSubject.setTitle(data.getTwoSubjectName());
            twoSubject.setParentId(pid);
            subjectService.save(twoSubject);
        }

    }

    /**
     * 读取头信息
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHead(Map<Integer, CellData> headMap, AnalysisContext context) {
        super.invokeHead(headMap, context);
    }

    //判断是否存在一级分类
    private Subject isExistOneSubject(SubjectService subjectService,String name){
        QueryWrapper<Subject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        Subject subject = subjectService.getOne(wrapper);
        return subject;
    }
    //判断是否存在二级分类
    private Subject isExistTwoSubject(SubjectService subjectService,String name,String pid){
        QueryWrapper<Subject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        Subject subject = subjectService.getOne(wrapper);
        return subject;
    }

    //执行完之后
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
